import logging

from models.models_dev import OpOrderGoodsTb as DevOpOrderGoodsTb
from models.models_prod import OpOrderGoodsTb as ProdOpOrderGoodsTb
from services.base_dev_common_service import BaseDevCommonService
from utils.obj_utils import ObjectUtil

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


class DevOrderGoodsTbService(BaseDevCommonService):
    def __init__(self):
        super().__init__(model_class=DevOpOrderGoodsTb, time_field='order_created_time')

    def add(self, prod_datas: list[ProdOpOrderGoodsTb], session=None):
        # 如果未提供session，则获取新的session
        if session is None:
            session = self.get_session()
            close_session = True
        else:
            close_session = False

        try:
            dev_orders = []
            for prod_data in prod_datas:
                dev_order_goods = DevOpOrderGoodsTb()
                ObjectUtil.copy_fields(dev_order_goods, prod_data,
                                       self.get_table_fields({'id', 'idx_created_timestamp'}))
                dev_orders.append(dev_order_goods)

            if not dev_orders:
                logger.warning("没有要插入的数据")
                return

            logger.info("添加 %d 条订单商品数据到数据库", len(dev_orders))
            session.add_all(dev_orders)
            session.commit()

        except Exception as e:
            session.rollback()
            logger.error("数据库操作失败: %s", str(e), exc_info=True)
            raise
        finally:
            if close_session and hasattr(session, 'close'):
                logger.info("关闭数据库连接")
                session.close()
